package setting

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-ini/ini"
	"gopkg.in/yaml.v2"
)

var (
	Cfg               *ini.File
	LoginInterface    string
	RunMode           string
	Run_enable_bucket string

	HTTPPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration

	PageSize     int
	IdentityKey  string
	ShareUrl     string
	ShareFlowUrl string

	AccessKeyID        string
	SecretAccessKey    string
	S3Region           string
	S3Bucket           string
	S3Host             string
	AccountId          string
	AIRootNodeTemplate string
	AISubNodeTemplate  string
	ApiKey             string
	ApiModel           string
	ApiModelList       string
	ApiUrl             string
	ApiType            string
	PrivilegeYaml      map[string]interface{}
)

type AWSS3 struct {
	AccessKeyID     string
	SecretAccessKey string
	S3Region        string
	S3Bucket        string
	S3Host          string
	AccountId       string
}

func GetAWSS3() AWSS3 {
	return AWSS3{
		AccessKeyID,
		SecretAccessKey,
		S3Region,
		S3Bucket,
		S3Host,
		AccountId,
	}
}

func GetReadTimeout() time.Duration {
	return ReadTimeout
}
func GetWriteTimeout() time.Duration {
	return WriteTimeout
}

func GetLoginurl() string {
	return LoginInterface
}
func GetHttpPort() int {
	return HTTPPort
}

// @types  f,flow ,m,mind
func GetShareUrl(types string) string {
	if types == "f" {
		return ShareFlowUrl
	}
	return ShareUrl
}

func GetprivKey() string {
	return IdentityKey
}

func init() {
	var err error
	env := os.Getenv("env")
	var configFilePath string
	fmt.Println("env:::::::::::::", env)

	// 根据环境变量决定读取哪个配置文件
	switch env {
	case "production":
		configFilePath = "conf/app.ini"
	case "dev":
		configFilePath = "conf/dev.ini"
	default:
		configFilePath = "conf/app.ini"
	}
	// configFilePath = "conf/dev.ini"
	Cfg, err = ini.Load(configFilePath)

	if err != nil {
		log.Fatalf("Fail to parse 'conf/app.ini': %v", err)
	}
	// 读取YAML配置文件
	PrivilegeData, err := ioutil.ReadFile("conf/config.yaml")
	if err != nil {
		log.Fatalf("Fail to parse 'conf/app.ini': %v", err)
	}

	// 解析YAML文件
	if err := yaml.Unmarshal(PrivilegeData, &PrivilegeYaml); err != nil {
		log.Fatalf("Fail to parse 'conf/config.yaml': %v", err)
	}

	gin.DisableConsoleColor()

	LoadBase()
	LoadApp()
	LoadAppS3()
	LoadServer()
	LoadAi()
}

func LoadBase() {
	RunMode = Cfg.Section("").Key("RUN_MODE").MustString("debug")
	Run_enable_bucket = Cfg.Section("").Key("ENABLE_BUCKET").MustString("R2")
	fmt.Println(Run_enable_bucket)
}

func LoadServer() {
	sec, err := Cfg.GetSection("server")
	if err != nil {
		log.Fatalf("Fail to get section 'server': %v", err)
	}
	HTTPPort = sec.Key("HTTP_PORT").MustInt(8000)
	ReadTimeout = time.Duration(sec.Key("READ_TIMEOUT").MustInt(60)) * time.Second
	WriteTimeout = time.Duration(sec.Key("WRITE_TIMEOUT").MustInt(60)) * time.Second

}

func LoadApp() {
	sec, err := Cfg.GetSection("app")
	if err != nil {
		log.Fatalf("Fail to get section 'app': %v", err)
	}
	LoginInterface = sec.Key("LoginInterface").MustString("http://")
	IdentityKey = sec.Key("IDENTITY_KEY").MustString("!@)*#)!@U#@*!@!)")
	PageSize = sec.Key("PAGE_SIZE").MustInt(10)
	ShareUrl = sec.Key("ShareUrl").MustString("http://localhost")
	ShareFlowUrl = sec.Key("ShareFlowUrl").MustString("http://localhost")
}
func LoadAppS3() {
	sec, err := Cfg.GetSection("S3")
	if Run_enable_bucket == "R2" {
		sec, err = Cfg.GetSection("R2")
	}

	if err != nil {
		log.Fatalf("Fail to get section 'app': %v", err)
	}

	AccessKeyID = sec.Key("AccessKeyID").MustString("")
	SecretAccessKey = sec.Key("SecretAccessKey").MustString("")
	S3Region = sec.Key("S3Region").MustString("")
	S3Bucket = sec.Key("S3Bucket").MustString("auto")
	S3Host = sec.Key("S3Host").MustString("")
	AccountId = sec.Key("AccountId").MustString("")

}

func LoadAi() {
	sec, err := Cfg.GetSection("ai")

	if err != nil {
		log.Fatalf("GetSection file: %v", err)
	}

	rootTemplatePath := sec.Key("AIRootNodeTemplatePath").MustString("")
	subTemplatePath := sec.Key("AISubNodeTemplatePath").MustString("")
	print(rootTemplatePath)
	rootTemplateContent, err := os.ReadFile(rootTemplatePath)
	if err != nil {
		log.Fatalf("Fail to read root node template file: %v", err)
	}
	subTemplateContent, err := os.ReadFile(subTemplatePath)
	if err != nil {
		log.Fatalf("Fail to read sub node template file: %v", err)
	}
	AIRootNodeTemplate = string(rootTemplateContent)
	AISubNodeTemplate = string(subTemplateContent)
	ApiKey = sec.Key("api_key").MustString("")
	ApiModel = sec.Key("api_model").MustString("")
	ApiModelList = sec.Key("api_model_list").String()
	ApiUrl = sec.Key("api_url").MustString("")
	ApiType = sec.Key("api_type").MustString("")

}
